package com.qiguliuxing.dts.core.manager;

import com.alibaba.fastjson.JSONObject;
import com.qiguliuxing.dts.common.constant.RedisKeyConsts;
import com.qiguliuxing.dts.core.redis.RedisServiceUtil;
import com.qiguliuxing.dts.common.util.CharUtils;

import java.text.MessageFormat;
import java.time.LocalDateTime;

/**
 * 维护用户token
 */
public class UserTokenManager {

	public static Integer getUserId(String token) {
		UserToken userToken = JSONObject.toJavaObject(RedisServiceUtil.get(token), UserToken.class);
		if (userToken == null) {
			return null;
		}

		if (userToken.getExpireTime().isBefore(LocalDateTime.now())) {
			RedisServiceUtil.del(token);
			String key = MessageFormat.format(RedisKeyConsts.WX_LOGIN_USER, new Object[]{String.valueOf(userToken.getUserId())});

			RedisServiceUtil.del(key);
			return null;
		}

		return userToken.getUserId();
	}

	public static UserToken generateToken(Integer id, String sessionKey) {
		UserToken userToken;

		// userToken = idMap.get(id);
		// if(userToken != null) {
		// tokenMap.remove(userToken.getToken());
		// idMap.remove(id);
		// }

		String token = CharUtils.getRandomString(32);
		while (RedisServiceUtil.hasKey(token)) {
			token = CharUtils.getRandomString(32);
		}

		LocalDateTime update = LocalDateTime.now();
		LocalDateTime expire = update.plusDays(1);

		userToken = new UserToken();
		userToken.setSessionKey(sessionKey);
		userToken.setToken(token);
		userToken.setUpdateTime(update);
		userToken.setExpireTime(expire);
		userToken.setUserId(id);
		RedisServiceUtil.set(token, userToken);
		String key = MessageFormat.format(RedisKeyConsts.WX_LOGIN_USER, new Object[]{String.valueOf(id)});
		RedisServiceUtil.set(key, userToken);
		return userToken;
	}

	public static String getSessionKey(Integer userId) {
		String key = MessageFormat.format(RedisKeyConsts.WX_LOGIN_USER, new Object[]{String.valueOf(userId)});
		UserToken userToken = JSONObject.toJavaObject(RedisServiceUtil.get(key), UserToken.class);
		if (userToken == null) {
			return null;
		}

		if (userToken.getExpireTime().isBefore(LocalDateTime.now())) {
			RedisServiceUtil.del(userToken.getToken());
			RedisServiceUtil.del(key);
			return null;
		}

		return userToken.getSessionKey();
	}

	public static void removeToken(Integer userId) {
		String key = MessageFormat.format(RedisKeyConsts.WX_LOGIN_USER, new Object[]{String.valueOf(userId)});
		UserToken userToken = JSONObject.toJavaObject(RedisServiceUtil.get(key), UserToken.class);
		String token = userToken.getToken();
		RedisServiceUtil.del(key);
		RedisServiceUtil.del(token);
	}
}
